﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Q_SMS.Response;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Q_SMS.Sender
{
   static class SMSSingleSender
    {
        const string _url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms";
        /*请求包体
         * {
         * "tel": {
         * "nationcode": "86", 
         * "mobile": "13788888888"
         * },
         * "type": 0, 
         * "msg": "你的验证码是1234", 
         * "sig": "fdba654e05bc0d15796713a1a1a2318c", 
         * "time": 1479888540,
         * "extend": "",
         * "ext": ""
         * }*/
        /// <summary>
        /// 普通发送
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appkey"></param>
        /// <param name="type">
        /// 发送类别
        /// -1、模板信息(为-1时参数templateId与parms为必填项)
        /// 0、普通短信
        /// 1、营销短信
        /// </param>
        /// <param name="nationCode"></param>
        /// <param name="phoneNumber"></param>
        /// <param name="msg"></param>
        /// <param name="extend"></param>
        /// <param name="ext"></param>
        /// <param name="sign">短信签名</param>
        /// <param name="templateId"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static SMSSingleResult Send(string appid, string appkey, int type, string nationCode, string phoneNumber, string msg, string extend, string ext, string sign, string templateId, List<string> parms)
        {
            long random = Tools.GetRandom(); //util.GetRandom();
            long curTime = Tools.GetCurTime();

            // 按照协议组织 post 请求包体
            JObject data = new JObject();

            JObject tel = new JObject();
            tel.Add("nationcode", nationCode);
            tel.Add("mobile", phoneNumber);
            data.Add("tel", tel);
            data.Add("sig", Tools.StrToHash(String.Format(
                    "appkey={0}&random={1}&time={2}&mobile={3}",
                    appkey, random, curTime, phoneNumber)));
            if (type != -1)
            {
                //普通发送
                data.Add("msg", msg);
                data.Add("type", type);

            }
            else
            {
                //模板消息
                data.Add("tpl_id", templateId);
                data.Add("params", Tools.ParmsToJSONArray(parms));
                data.Add("sign", sign);
            }


            data.Add("time", curTime);
            data.Add("extend", extend);
            data.Add("ext", ext);

            string wholeUrl = _url + "?sdkappid=" + appid + "&random=" + random;
            HttpWebRequest request = Tools.GetPostHttp(wholeUrl);
            byte[] requestData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
            request.ContentLength = requestData.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(requestData, 0, requestData.Length);
            requestStream.Close();

            // 接收返回包
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string responseStr = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            SMSSingleResult result;
            if (HttpStatusCode.OK == response.StatusCode)
            {
                result = JsonConvert.DeserializeObject<SMSSingleResult>(responseStr);
            }
            else
            {
                result = new SMSSingleResult();
                result.Result = -1;
                result.Errmsg = "http error " + response.StatusCode + " " + responseStr;
            }
            return result;
        }
    }
}
